<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
          <z-form-item :datas="fieldArr" :form="queryParam" :gutter="8" :submitAction="{show: true, toggle: true, span: 6}" @onSubmit="onQuery"
            @onReset="onResetForm" @change="onChange">
            <template slot="slots-time">
              <a-radio-group buttonStyle="solid" v-model="queryParam.updateType">
                <a-radio-button v-for="(item, key) in options" :key="key" :value="item.value">
                  {{ item.text }}
                </a-radio-button>
              </a-radio-group>
              <span style="margin-left: 10px" v-if="queryParam.updateType === '0'">
                <a-date-picker
                  v-model="queryParam.startTime"
                  placeholder="开始日期"
                  :disabled-date="disabledStartDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :show-time="false"
                  @openChange="handleOpenChange($event, 'start')"
                />
                <span style="padding:0 4px;">-</span>
                <a-date-picker
                  v-model="queryParam.endTime"
                  placeholder="结束日期"
                  :disabled-date="disabledEndDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :show-time="false"
                  :open="endOpen"
                  @openChange="handleOpenChange($event, 'end')"
                />
              </span>
            </template>
          </z-form-item>
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 表格展示 -->
      <div class="table-page-content">
        <z-table
          ref="table"
          rowKey="id"
          :showAlert="false"
          :showSelection="false"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        />
      </div>
      <!--弹窗区域-->
      <dispose-modal ref="disposeModal" :riskLevelDatas="riskLevelDatas" @ok="modalFormOk" />
    </a-card>
  </div>
</template>

<script>
import * as alarmServiceApi from '@/api/sjsk/alarmService'
import disposeModal from './modules/alarmDisposeModal'

export default {
  components: { disposeModal },
  data() {
    return {
      loading: false,
      endOpen: false,
      selectKeys: [],
      queryParam: {},
      options: [
        { value: '5', text: '全部' },
        { value: '2', text: '今天' },
        { value: '1', text: '昨天' },
        { value: '3', text: '近三天' },
        { value: '4', text: '近七天' },
        { value: '0', text: '自定义' },
      ],
      statusDatas: [
        // { text:"请选择", value:"" },
        { text:"待批", value:"1" },
        { text:"审批中", value:"2" },
        { text:"驳回", value:"3" },
        { text:"通过", value:"4" },
        { text:"关闭", value:"5" },
      ],
      disposalStatusDatas: [
        // { text:"请选择", value:"" },
        { text:"已处置", value:"1" },
        { text:"未处置", value:"0" }
      ],
      riskLevelDatas: [
        // { text:"请选择", value:"" },
        { text:"高危", value:"1" },
        { text:"中危", value:"2" },
        { text:"低危", value:"3" }
      ],
      fieldArr: [
        { label: '任务名称', prop: 'taskName', tagType: 'input', span: 8 },
        { label: '任务编号', prop: 'taskCode', tagType: 'input', span: 8 },
        { label: '状态', prop: 'status', tagType: 'dict-select', dictOptions: [], span: 8, toggle: false },
        { label: '处置情况', prop: 'disposalStatus', tagType: 'dict-select', dictOptions: [], span: 8, toggle: false },
        { label: '创建人', prop: 'createBy', tagType: 'input', span: 8, toggle: false  },
        { label: '风险程度', prop: 'riskLevel', tagType: 'dict-select', dictCode: 'risk_level', span: 8, toggle: false },
        { label: '所属机构', prop: 'affiliatedOrganizations', tagType: 'linkage-area', span: 16,toggle: false },
        { label: '创建时间', prop: 'time', toggle: false },
      ],
      columns: [
        { title: '序号', dataIndex: 'order', width: 60, align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` //序号分页后连续
        },
        {
          title: '任务编号',
          dataIndex: 'taskCode',
          width: 110,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: 110,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '风险程度',
          dataIndex: 'riskLevel',
          width: 70,
          align: 'center',
          customRender:(text)=> {
            return (
              <span class={text==1 ? 'text_color_2' : text==2 ? 'text_color_3' : text==3 ? 'text_color_4' : ''}>
                {this.$filterDictTextByCache('risk_level', text)}
              </span>
            )
          }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          width: 80,
          align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 120,
          align: 'center',
        },
        {
          title: '所属机构',
          dataIndex: 'affiliatedOrganization',
          width: 80,
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 60,
          align: 'center',
          customRender:(text)=> {
            return (
              <span class={text==1 ? 'text_color_4' : text==2 ? 'text_color_3' : text==3 ? 'text_color_2' : text==4 ? 'text_color_1' : text==5 ? 'text_color_5' : ''}>
                { this.$options.filters.filterArray(text, this.statusDatas, 'value', 'text') }
              </span>
            )
          }
        },
        {
          title: '处置情况',
          dataIndex: 'disposalStatus',
          width: 80,
          align: 'center',
          customRender:(text)=> {
            return this.$options.filters.filterArray(text, this.disposalStatusDatas, 'value', 'text')
          }
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.clickPush(record)}> 查看 </a-button>
                {record.disposalStatus==1?
                <a-button type="link" style={'padding:0'} onClick={(event) => this.dispose(record, 'details')}> 处置结果 </a-button>
                : <a-button type="link" style={'padding:0'} onClick={(event) => this.dispose(record, 'add')}> 处置 </a-button>
                }
                {record.status!==2 && record.status!==5 && record.status!==5?
                  <a-button type="link" style={'padding:0 0 0 5px'} onClick={(event) => this.close(record)}> 关闭 </a-button>
                :null}
              </a-space>
            )
          },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {}
    }
  },
  async mounted() {
    this.$set(this.queryParam, 'updateType', '5')
    this.fieldArr.forEach(item => {
      let d = [{ text:"请选择", value:"" }]
      if(item.prop==='status') {
        item.dictOptions = [...d, ...this.statusDatas]
      } 
      if(item.prop==='disposalStatus') {
        item.dictOptions = [...d, ...this.disposalStatusDatas]
      }
    })
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.queryParam = {}
      this.$set(this.queryParam, 'updateType', '5')
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      // this.$set(this.queryParam, 'userRole', 2)
      let {affiliatedOrganizations, ...dataParam} = this.queryParam // 剔除affiliatedOrganizations元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      alarmServiceApi
        .getTaskList(queryParam)
        .then((res) => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 弹窗成功接收
    modalFormOk() {
      this.onQuery()
    },
    // 查看
    clickPush(record) {
      let id = record instanceof Object?record.id: record
      let path = id?`/examine/details/41/${id}`:``
      this.$router.push({
        path: path
      })
    },
    // 处置、处置查看
    dispose(record, type) {
      this.$refs.disposeModal.show(record, type)
    },
    //关闭
    close(record) {
      let that = this
      this.$confirm({
        title: `确认关闭该告警事件？`,
        onOk() {
          alarmServiceApi.taskClose(record.id).then((res) => {
            if (res.success) {
              that.$message.success(res.message?res.message:'操作成功')
              that.modalFormOk()
            } else {
              that.$message.warn(res.message?res.message:'操作失败')
            }
          }).catch(e=>{
            that.$message.warn("操作失败！")
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'confirm',
      })
    },
    onChange(prop, value) {
      if(prop ==='affiliatedOrganizations') {
        console.log(value)
        let data = value? value.filter(item=>{ return item }): []
        this.$set(this.queryParam,'affiliatedOrganization', data.toString())
      }
    },
    // 创建时间-自定义开始日期【不可选择的日期】
    disabledStartDate(startValue) {
      const endValue = Object.keys(this.queryParam).length > 0 && this.queryParam.endTime
        ? this.$JMoment(this.queryParam.endTime) : null
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    // 创建时间-自定义结束日期【不可选择的日期】
    disabledEndDate(endValue) {
      const startValue = Object.keys(this.queryParam).length > 0 && this.queryParam.startTime
      ? this.$JMoment(this.queryParam.startTime) : null
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    // 创建时间-自定义日期【控制弹层是否展开】
    handleOpenChange(open, status) {
      if (status==='start' && !open) {
        this.endOpen = true
      }
      if (status==='end') {
        this.endOpen = open
      }
    },
  },
}
</script>
<style scoped lang="less">
.text_color_1 {
  color: #70B603;
}
.text_color_2 {
  color: #d9001b;
}
.text_color_3 {
  color: #f59a23;
}
.text_color_4 {
  color: #02a7f0;
}
.text_color_5 {
  color: #aeaeae;
}
</style>
